package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

   @Autowired
   private StrategyRepository strategyRepository;

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        repository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {

        repository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {


        return repository.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {

        //查询封装类
        Query query = new Query();

        //分页需要的数据: total -- 所有数据
        long total = template.count(query, StrategyCatalog.class);
        if (total == 0){
            return Page.empty();
        }
        //分页数据 , currentPage , pageSite
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");
        query.with(pageable);
        //当前页显示的数据
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        //list Pageable total 封装三个数据,返回给页面
        return new PageImpl(list,pageable,total);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        Destination des = destinationService.get(strategyCatalog.getDestId());
        strategyCatalog.setDestName(des.getName());
        //判断是否有id,有则修改,无则添加
        if (StringUtils.hasLength(strategyCatalog.getId())){

            this.update(strategyCatalog);
        }else {
            this.save(strategyCatalog);
        }
    }

    @Override
    public List<CatalogVO> queryGroupList() {


        List<CatalogVO> list = new ArrayList<>();
        //聚合查询
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg,Map.class);
        List<Map> datas = result.getMappedResults(); //将结果转化成list<map>   map描述一行数据
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();

            vo.setDestName(data.get("_id").toString());  //id
            List<Object> names = (List<Object>) data.get("names");  //攻略分类的名称集合
            List<Object> ids = (List<Object>) data.get("ids");  //攻略分类的ids集合

            List<StrategyCatalog> catalogList = new ArrayList<>(); //攻略分类对象

            for(int i = 0;i < names.size(); i++){
                StrategyCatalog sc = new StrategyCatalog();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                sc.setId(id);
                sc.setName(name);
                catalogList.add(sc);
            }
            vo.setCatalogList(catalogList);
            list.add(vo);
        }
        return list;
    }

    /**
     * 某个目的地概况 和 攻略
     * @param destId
     * @return
     */
    @Override
    public List<StrategyCatalog> queryByCatalogs(String destId) {

        //根据destId查询广州的概况,返回list集合
       List<StrategyCatalog> list = repository.findByDestId(destId);
       //遍历查询,根据名字去查询攻略,然后封装到 数组中,将查到的数据设置到该数组中
        for (StrategyCatalog Catalogs : list) {
            List<Strategy> strategies = strategyRepository.findByCatalogName(Catalogs.getName());
            Catalogs.setStrategies(strategies);

        }
        return list;
    }


}
